<template>
    <view class="view">
        <image class="img" :src="url" mode="widthFix" />
        <!--  -->
        <view class="silder" v-if="type === 7 && !ok">
            <u-slider
                @change="changeAge($event)"
                step="5"
                min="20"
                max="80"
                v-model="age"
            ></u-slider>
            <view class="line">当前变换年龄:{{ age }}</view>
        </view>
        <!--  -->
        <view class="bottom">
            <u-button
                @click="croppImage()"
                class="next"
                size="medium"
                type="primary"
                plain
                >选择图片</u-button
            >
            <block v-if="url">
                <u-button
                    v-if="!ok"
                    @click="next()"
                    class="next"
                    size="medium"
                    type="primary"
                    plain
                >
                    <!-- #ifdef MP -->
                    {{ needOpenAd ? "观看广告查看结果" : "下一步" }}
                    <!-- #endif -->
                    <!-- #ifndef MP -->
                    下一步
                    <!-- #endif -->
                </u-button>
                <u-button
                    v-if="ok"
                    @click="save()"
                    class="next"
                    size="medium"
                    type="primary"
                    plain
                    >保存</u-button
                >
            </block>

            <!-- <u-button
                v-if="ok"
                @click="back()"
                class="next"
                size="medium"
                type="primary"
                plain
                >继续处理照片</u-button
            > -->
        </view>

        <u-modal
            @confirm="confirm"
            show-cancel-button
            v-model="show"
            :content="'当前可用次数为0，请前往充值'"
        ></u-modal>
        <!--  -->
       <!-- <u-modal
            show-cancel-button
            v-model="showTestModal"
            :content="testModalContext"
            :confirm-text="testConfirmText"
            :cancel-text="testCancelText"
            cancel-color="rgb(41, 121, 255)"
            confirm-color="rgb(41, 121, 255)"
            @confirm="testConfirm()"
            @cancel="testCancel()"
        ></u-modal> -->
    </view>
</template>

<script>
import getToken from "../../tools/token.js";
import {
    hightLightPhoto,
    pickColorPhoto,
    scalePhoto,
    animationHead,
    pickResetPhoto,
    genderTransformation,
    genderChangeAgePic,
} from "../../tools/api";
import { base64ToPath, pathToBase64 } from "image-tools";
import { mapGetters, mapMutations } from "vuex";
function getNewFileId() {
    return Date.now() + String(index++);
}
const base64TurnToPath = base64 => {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: "加载中...",
            mask: true,
        });
        if (typeof uni === "object" && uni.canIUse("getFileSystemManager")) {
            let filePath =
                qq.env.USER_DATA_PATH + "/" + new Date().getTime() + ".jpg";
            let fs = uni.getFileSystemManager();
            fs.writeFile({
                filePath: filePath,
                data: base64.replace(/^data:\S+\/\S+;base64,/, ""),
                encoding: "base64",
                success: () => {
                    resolve(filePath);
                },
                fail: error => {
                    reject(error);
                },
                complete: () => uni.hideLoading(),
            });
        }
    });
};

export default {
    data() {
        return {
            url: "",
            w: 0,
            h: 0,
            isCut: false,
            base64: "",
            ok: false,
            type: 1,
            show: false,
            imageInfo: [],
            config: {},
            showTestModal: false,
            testModalContext: "请选择转换方式",
            testConfirmText: "男变女",
            testCancelText: "女变男",
            ageArray: [20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80],
            ageIndex: 0,
            age: 20,
            needOpenAd: true,
        };
    },
    methods: {
        changeAge() {
            this.ok = false;
        },
        confirm() {
            uni.switchTab({ url: "/pages/member/member" });
        },
        // 校验图片
        checkedPicture() {
            return new Promise((resolve, reject) => {
                let pkgName = "com.qq.oldpicture";
                uni.request({
                    url: `https://cs.snmi.cn/user/GetQqToken?pkgName=${pkgName}&appChannel=qq&appVersion=100&deviceId=`,
                    method: "GET",
                    sslVerify: true,
                    success: ({ data, statusCode, header }) => {
                        if (data.Code === 200) {
                            resolve(data.Detail);
                        } else {
                            reject(data);
                        }
                    },
                    fail: error => {
                        reject(error);
                    },
                });
            });
        },
        async croppImage() {
            this.ok = false;

            // 裁剪功能
            if (this.type == 999) {
                this.$u.route({
                    // 关于此路径，请见下方"注意事项"
                    url:
                        "/uview-ui/components/u-avatar-cropper/u-avatar-cropper",
                    // 内部已设置以下默认参数值，可不传这些参数
                    params: {
                        // 输出图片宽度，高等于宽，单位px
                        destWidth: this.w,
                        // 裁剪框宽度，高等于宽，单位px
                        rectWidth: this.w,
                        // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
                        fileType: "jpg",
                    },
                });
            } else {
                uni.chooseImage({
                    sizeType: ["compressed"],
                    sourceType: ["album", "camera"],
                    success: async ({ tempFilePaths }) => {
                        let path = tempFilePaths[0];
                        this.needOpenAd = true;
                        // 获取图片信息
                        uni.getImageInfo({
                            src: path,
                            success: ({ width, height }) => {
                                this.imageInfo = [
                                    {
                                        width: width * 0.8,
                                        top: width * 0.8 + 100,
                                        height: height * 0.8,
                                        left: height * 0.8 + 100,
                                    },
                                ];
                            },
                            fail: error => {},
                        });
                        /* #ifdef MP */
                        // 校验图片
                        uni.showLoading({
                            title: "图片检测中...",
                            mask: true,
                        });
                        let token = await this.checkedPicture();
                        uni.uploadFile({
                            url: `https://api.q.qq.com/api/json/security/ImgSecCheck?access_token=${token}&appid=1111692157`,
                            fileType: "image",
                            filePath: path,
                            name: "media",
                            formData: {
                                access_token: token,
                                appid: 1111692157,
                            },
                            success: ({ data }) => {
                                const { errCode } = JSON.parse(data);
                                if (errCode === 87014) {
                                    uni.showModal({
                                        title: "提示",
                                        content: "图片内容违规,请重新上传!",
                                        showCancel: false,
                                    });
                                } else {
                                    uni.showToast({
                                        title: "图片检测通过",
                                        icon: "success",
                                        mask: true,
                                    });
                                    // 转base64
                                    if (this.needUrl === 0) {
                                        uni.getFileSystemManager().readFile({
                                            filePath: path, //选择图片返回的相对路径
                                            encoding: "base64", //编码格式
                                            success: res => {
                                                this.url =
                                                    "data:image/png;base64," +
                                                    res.data;
                                            },
                                            fail: () => {
                                                uni.showToast({
                                                    title: "文件读取失败",
                                                    icon: "none",
                                                    mask: true,
                                                });
                                            },
                                        });
                                    } else {
                                        this.uploadImgs(path);
                                    }
                                }
                            },
                            fail: error => {
                                console.log(error);
                                uni.showToast({
                                    title: "图片检测失败",
                                    icon: "success",
                                    mask: true,
                                });
                            },
                            complete: () => uni.hideLoading(),
                        });

                        /* #endif */

                        // #ifndef MP
                        if (this.needUrl === 0) {
                            this.url = await pathToBase64(path);
                        }

                        if (this.needUrl === 1) {
                            this.uploadImgs(path);
                        }

                        // #endif
                    },
                    fail: error => {},
                });
            }
        },
        uploadImgs(path) {
            uni.showLoading({
                title: "文件上传中",
                mask: true,
            });
            uni.uploadFile({
                // #ifdef H5
                url: "/cssnmi/oss/uploadtempfiles",
                // #endif
                // #ifndef H5
                url: "https://cs.snmi.cn/oss/uploadtempfiles",
                // #endif
                filePath: path,
                name: "image",
                success: res => {
                    let data = JSON.parse(res.data);
                    if (data.Code !== 1) {
                        uni.showToast({
                            title: "图片上传失败,请重试",
                            icon: "success",
                            mask: true,
                        });
                        return;
                    }
                    uni.showToast({
                        title: "图片上传成功",
                        icon: "success",
                        mask: true,
                    });
                    this.url = data.Detail;
                },
                fail: err => {
                    console.log(err);
                    uni.showToast({
                        title: "文件上传失败,请重试",
                        icon: "none",
                        mask: true,
                    });
                },
                complete: () => uni.hideLoading(),
            });
        },
        back() {
            uni.navigateBack({
                delta: 2,
            });
        },
        async save() {
            uni.showLoading({
                title: "保存中...",
                mask: true,
            });
            const httpReg = /^((http|https):\/\/)+([\w\-])+\.(tmall|taobao).com/;
            // #ifdef APP-PLUS
            if (this.needUrl === 0) {
                let res = await base64ToPath(this.url);
                uni.saveImageToPhotosAlbum({
                    filePath: res,
                    success: function () {
                        uni.showToast({
                            title: "保存成功",
                            duration: 2000,
                        });
                    },
                    fail: () => {
                        uni.showToast({
                            title: "保存失败",
                            duration: 2000,
                        });
                    },
                    complete: () => uni.hideLoading(),
                });
            } else {
                uni.downloadFile({
                    url: this.url,
                    success: ({ tempFilePath, statusCode }) => {
                        if (statusCode === 200) {
                            uni.saveImageToPhotosAlbum({
                                filePath: tempFilePath,
                                success: result => {
                                    uni.showToast({
                                        title: "图片保存成功",
                                        icon: "success",
                                        mask: true,
                                    });
                                },
                                fail: error => {
                                    uni.showToast({
                                        title: "图片保存失败",
                                        icon: "success",
                                        mask: true,
                                    });
                                },
                                complete: () => uni.hideLoading(),
                            });
                        } else {
                            uni.showToast({
                                title: "图片下载失败",
                                icon: "success",
                                mask: true,
                            });
                            uni.hideLoading();
                        }
                    },
                    fail: error => {
                        uni.showToast({
                            title: "图片下载失败",
                            icon: "success",
                            mask: true,
                        });
                        uni.hideLoading();
                    },
                });
            }
            // #endif

            // #ifdef MP
            if (httpReg.test(this.url)) {
                uni.downloadFile({
                    url: this.url,
                    success: ({ tempFilePath, statusCode }) => {
                        if (statusCode === 200) {
                            uni.saveImageToPhotosAlbum({
                                filePath: tempFilePath,
                                success: result => {
                                    uni.showToast({
                                        title: "保存成功",
                                        duration: 2000,
                                    });
                                },
                                fail: error => {
                                    uni.showToast({
                                        title: "保存失败",
                                        duration: 2000,
                                    });
                                },
                            });
                        }
                    },
                    fail: error => {
                        uni.showToast({
                            title: "保存失败",
                            duration: 2000,
                        });
                        uni.hideLoading();
                    },
                });
            } else {
                uni.getSetting({
                    success: res => {
                        console.log(res);
                        if (!res.authSetting["scope.writePhotosAlbum"]) {
                            uni.authorize({
                                scope: "scope.writePhotosAlbum",
                                success: () => {
                                    uni.saveImageToPhotosAlbum({
                                        filePath: this.url,
                                        success: () => {
                                            console.log("文件保存成功", path);
                                            uni.showToast({
                                                title: "保存成功",
                                                duration: 2000,
                                            });
                                        },
                                        fail: () => {
                                            console.log("文件保存失败", path);
                                            uni.showToast({
                                                title: "保存失败",
                                                duration: 2000,
                                            });
                                        },
                                        complete: () => uni.hideLoading(),
                                    });
                                },
                            });
                        } else {
                            uni.saveImageToPhotosAlbum({
                                filePath: this.url,
                                success: () => {
                                    uni.showToast({
                                        title: "保存成功",
                                        duration: 2000,
                                    });
                                },
                                fail: () => {
                                    uni.showToast({
                                        title: "保存失败",
                                        duration: 2000,
                                    });
                                },
                                complete: () => uni.hideLoading(),
                            });
                        }
                    },
                });
            }
            // #endif

            // #ifdef H5
            let a = document.createElement("a");
            if (!httpReg.test(this.url)) {
                a.download = new Date().getTime() + ".jpg";
                a.href = await pathToBase64(this.url);
                a.click();
                uni.hideLoading();
            } else {
                console.log("*********");
                let result = await base64ToPath(this.url);
                a.href = await result;
                a.download = new Date().getTime() + ".jpg";
                await a.click();
                uni.hideLoading();
            }

            // #endif
        },
        chooseImage() {
            uni.chooseImage({
                count: 1, //默认9
                sizeType: ["compressed"],
                success: chooseImageRes => {
                    this.url = chooseImageRes.tempFilePaths[0];
                    // this.$refs.cropper.open();
                },
            });
        },
        replaceHead(str) {
            return str
                .replace("data:image/png;base64,", "")
                .replace("data:image/jpeg;base64,", "");
        },
        async next() {
            // #ifndef MP
            if (this.getUseCount === 0) {
                this.show = true;
                return;
            }
            // #endif
            // #ifdef MP-QQ
            if (this.needOpenAd) {
                this.playVideo();
            } else {
                this.runTest();
            }
            // #endif
            // #ifndef MP
            this.runTest();
            // #endif
            // #ifdef MP-WEIXIN
            this.runTest();
            // #endif
        },
        async runTest() {
            let { access_token } = await getToken();
            console.log(access_token);
            if (this.type === 1) {
                try {
                    let res = await pickColorPhoto({
                        token: access_token,
                        image: this.replaceHead(this.url),
                    });
                    this.runSuccess(res);
                } catch (e) {
                    //TODO handle the exception
                    console.log(e);
                }
            }
            if (this.type === 2) {
                try {
                    let res = await hightLightPhoto({
                        token: access_token,
                        image: this.replaceHead(this.url),
                    });
                    this.runSuccess(res);
                } catch (e) {
                    //TODO handle the exception
                    console.log(e);
                }
            }
            if (this.type === 3) {
                try {
                    let res = await scalePhoto({
                        token: access_token,
                        image: this.replaceHead(this.url),
                    });
                    this.runSuccess(res);
                } catch (e) {
                    //TODO handle the exception
                    console.log(e);
                }
            }
            if (this.type === 4) {
                try {
                    let res = await animationHead({
                        token: await access_token,
                        image: this.replaceHead(this.url),
                    });
                    // console.log(res, "百度返回数据");

                    this.runSuccess(res);
                } catch (e) {
                    //TODO handle the exception
                    console.log(e);
                }
            }
            if (this.type === 5) {
                try {
                    let res = await pickResetPhoto({
                        token: access_token,
                        image: this.replaceHead(this.url),
                        /* rectangle: [
                            { width: 92, top: 95, height: 36, left: 543 },
                        ], */
                        rectangle: this.imageInfo,
                    });
                    console.log(res, "百度返回数据---");

                    this.runSuccess(res);
                } catch (e) {
                    //TODO handle the exception
                    console.log(e);
                }
            }
            if (this.type === 6) {
                this.showTestModal = true;
            }
            if (this.type === 7) {
                if (this.needUrl === 1) {
                    try {
                        let path = await genderChangeAgePic({
                            url: this.url,
                            age: this.age,
                        });
                        console.log(path, "***--**");
                        this.url = await path;
                        // #ifdef MP
                        this.runSuccess({ image: this.url });
                        // #endif
                        // #ifndef MP
                        this.runSuccess(0);
                        // #endif
                    } catch (e) {
                        uni.showToast({
                            title: "失败,请重试",
                            duration: 2000,
                        });
                    }
                }
            }
        },
        // 性别转换
        async transformBoyWidthGirl(mode) {
            uni.showLoading({
                title: "加载中...",
                mask: true,
            });
            try {
                console.log(1223456767897);
                let path = await genderTransformation({
                    url: this.url,
                    mode: mode,
                });
                this.url = await path;
                uni.hideLoading();

                // #ifdef MP
                this.runSuccess({ image: this.url });
                // #endif
                // #ifndef MP
                this.runSuccess(0);
                // #endif
            } catch (e) {
                uni.showToast({
                    title: "转换失败，请重试",
                    icon: "none",
                    mask: true,
                });
                uni.hideLoading();
                this.runSuccess();
            }
        },
        async testCancel() {
            // 人脸转换
            if (this.type === 6) {
                this.transformBoyWidthGirl(1);
            }
        },
        async testConfirm() {
            // 人脸转换
            if (this.type === 6) {
                this.transformBoyWidthGirl(0);
            }
        },
        async runSuccess(res) {
            if (res.image || res === 0) {
                uni.showToast({
                    title: "成功",
                    duration: 2000,
                });
                this.ok = true;
                // #ifdef MP-QQ
                this.url = await base64TurnToPath(res.image);
                // #endif
                if (this.needUrl === 0) {
                    // #ifdef H5|APP-PLUS
                    this.url = "data:image/png;base64," + res.image;
                    this.updateCount(-1);
                    // #endif
                } else {
                    this.updateCount(-1);
                }
            } else {
                uni.showToast({
                    title: "失败,请重试",
                    duration: 2000,
                });
            }
        },
        // https://api.q.qq.com/api/getToken?grant_type=client_credential&appid=1111692157&secret=c16SeQ1XQrtK9RJb
        playVideo() {
            // #ifdef MP-QQ
            let videoAd = qq.createRewardedVideoAd({
                adUnitId: "fb323503f5bfd9fa84383bf87eb86bee",
            });
            videoAd.onError(function (res) {
                console.log("videoAd onError", res);
            });
            videoAd.onLoad(function (res) {
                console.log("videoAd onLoad", res);
            });
            videoAd.onClose(res => {
                if (res.isEnded) {
                    this.runTest();
                    this.needOpenAd = false;
                }
            });
            videoAd
                .load()
                .then(() => {
                    console.log("激励视频加载成功");
                    videoAd
                        .show()
                        .then(() => {
                            console.log("激励视频 广告显示成功");
                        })
                        .catch(err => {
                            console.log("激励视频 广告显示失败");
                        });
                })
                .catch(err => {
                    console.log("激励视频加载失败");
                });
            // #endif
        },
        // 小程序端  数据过大 拆分数据
        splitImageBase64ToArr(base64) {
            let arr = [];
            let d = base64.length / 5;
            for (let i = 0; i <= d; i++) {
                arr.push(base64.slice(i * 5, (i + 1) * 5));
            }
            return arr;
        },
        fail() {
            uni.navigateBack({
                delta: 2,
            });
        },
        async getImage(e) {
            // #ifdef APP-PLUS
            this.url = await pathToBase64(e);
            // #endif
            // #ifndef APP-PLUS
            this.url = e;
            // #endif
            this.isCut = true;
        },
        ...mapMutations(["updateCount"]),
    },
    async onLoad(o) {
        uni.$on("uAvatarCropper", async path => {
            this.url = path;
            // #ifdef APP-PLUS
            this.url = await pathToBase64(path);
            // #endif
        });
        this.url = o.url;
        this.type = o.type * 1;
        this.needUrl = o.needUrl * 1;
        // this.config =
        const { windowWidth, windowHeight } = uni.getSystemInfoSync();
        this.w = (windowWidth / 4) * 3;
        this.h = (windowHeight / 4) * 3;
    },
    onReady() {
        this.croppImage();
        // #ifdef MP-QQ
        qq.showShareMenu({
            showShareItems: ["qq", "qzone", "wechatFriends", "wechatMoment"],
        });
        // #endif
    },
    computed: {
        ...mapGetters(["getUseCount"]),
    },
};
</script>
<style lang="scss" scoped>
page {
    padding: 28rpx;
    background-color: #f2f2f2;
    text-align: center;
}
.view {
    text-align: center;
    width: 100%;
}
.img {
    width: 80%;
    margin: 28rpx auto !important;
}
.silder {
    padding: 0 28rpx;
    .line {
        font-size: 28rpx;
        color: #ccc;
        margin: 28rpx;
    }
}
.bottom {
    display: flex;
    align-items: center;
    justify-content: center;
    .next {
        width: 500rpx;
        margin: 28rpx auto !important;
    }
}
image {
    width: 100%;
}
</style>
